<template>
  <view class="order-list-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">我的订单</text>
    </view>

    <!-- 订单状态选项卡 -->
    <view class="order-tabs">
      <view 
        class="tab-item" 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{ active: currentTab === index }"
        @click="changeTab(index)"
      >
        <text>{{tab}}</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-scroll" v-if="filteredOrders.length > 0">
      <view class="order-item" v-for="(order, index) in filteredOrders" :key="order._id">
        <view class="order-header">
          <view class="shop-info">
            <image :src="order.shopInfo.imgUrl" mode="aspectFill"></image>
            <text class="shop-name">{{order.shopInfo.name}}</text>
          </view>
          <text class="order-status">{{getStatusText(order.status)}}</text>
        </view>

        <!-- 新增下单时间显示 -->
        <view class="order-time">
          <text>下单时间：{{formatTime(order.createTime)}}</text>
        </view>

        <view class="order-products">
          <view class="product-item" v-for="(product, pIndex) in order.products" :key="pIndex">
            <image :src="product.imgUrl" mode="aspectFill"></image>
            <view class="product-info">
              <text class="product-name">{{product.name}} {{product.weight || ''}}</text>
              <view class="product-price-count">
                <text class="price">¥{{product.price}}</text>
                <text class="count">x{{product.count}}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="order-footer">
          <view class="order-total">
            <text>共{{getTotalCount(order)}}件商品 实付：</text>
            <text class="price">¥{{order.totalPrice.toFixed(2)}}</text>
          </view>

          <view class="order-actions">
            <view class="action-btn" v-if="order.status === 'pending'" @click="cancelOrder(index)">
              <text>取消订单</text>
            </view>
            <view class="action-btn primary" v-if="order.status === 'pending'" @click="payOrder(order)">
              <text>去支付</text>
            </view>
            <view class="action-btn" v-if="order.status === 'paid' || order.status === 'delivered'" @click="confirmReceive(index)">
              <text>确认收货</text>
            </view>
            <view class="action-btn" v-if="order.status === 'completed'" @click="deleteOrder(index)">
              <text>删除订单</text>
            </view>
          </view>
        </view>

        <!-- 删除地址显示部分 -->
      </view>
    </scroll-view>

    <!-- 空订单提示 -->
    <view class="empty-order" v-else>
      <image src="/static/imgs/empty-order.png" mode="aspectFit"></image>
      <text>暂无相关订单</text>
    </view>

    <!-- 返回首页按钮 -->
    <view class="back-to-home" v-if="filteredOrders.length > 0">
      <button @click="goToHomePage">返回首页</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabs: ['全部', '进行中', '已完成', '已取消'],
      currentTab: 0,
      orderList: []
    }
  },
  computed: {
    filteredOrders() {
      if (this.currentTab === 0) {
        return this.orderList;
      } else if (this.currentTab === 1) {
        return this.orderList.filter(order => order.status === 'pending' || order.status === 'paid' || order.status === 'delivered');
      } else if (this.currentTab === 2) {
        return this.orderList.filter(order => order.status === 'completed');
      } else {
        return this.orderList.filter(order => order.status === 'cancelled');
      }
    }
  },
  onLoad() {
    this.loadOrderList();
  },
  onShow() {
    // 每次显示页面时重新加载订单列表
    this.loadOrderList();
  },
  methods: {
    goBack() {
      uni.switchTab({
        url: '/pages/homepage/index'
      });
    },

    loadOrderList() {
      const orderList = uni.getStorageSync('orderList');
      if (orderList) {
        this.orderList = JSON.parse(orderList);
      }
    },

    changeTab(index) {
      this.currentTab = index;
    },

    getStatusText(status) {
      switch (status) {
        case 'pending':
          return '待支付';
        case 'paid':
          return '配送中';
        case 'delivered':
          return '已送达';
        case 'completed':
          return '已完成';
        case 'cancelled':
          return '已取消';
        default:
          return '未知状态';
      }
    },

    getTotalCount(order) {
      let count = 0;
      order.products.forEach(product => {
        count += product.count;
      });
      return count;
    },

    payOrder(order) {
      uni.navigateTo({
        url: `/pages/order/payment?orderId=${order._id}`
      });
    },

    cancelOrder(index) {
      uni.showModal({
        title: '提示',
        content: '确定要取消该订单吗？',
        success: (res) => {
          if (res.confirm) {
            this.orderList[index].status = 'cancelled';
            this.orderList[index].cancelTime = new Date().toISOString();

            uni.setStorageSync('orderList', JSON.stringify(this.orderList));

            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            });
          }
        }
      });
    },

    confirmReceive(index) {
      uni.showModal({
        title: '提示',
        content: '确认已收到商品？',
        success: (res) => {
          if (res.confirm) {
            this.orderList[index].status = 'completed';
            this.orderList[index].completeTime = new Date().toISOString();

            uni.setStorageSync('orderList', JSON.stringify(this.orderList));

            uni.showToast({
              title: '确认收货成功',
              icon: 'success'
            });
          }
        }
      });
    },

    deleteOrder(index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该订单吗？',
        success: (res) => {
          if (res.confirm) {
            this.orderList.splice(index, 1);
            uni.setStorageSync('orderList', JSON.stringify(this.orderList));

            uni.showToast({
              title: '订单已删除',
              icon: 'success'
            });
          }
        }
      });
    },

    goToHomePage() {
      uni.switchTab({
        url: '/pages/homepage/index'
      });
    },

    // 格式化时间的方法
    formatTime(time) {
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    }
  }
}
</script>

<style lang="scss">
.order-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;

  .back-btn {
    margin-right: 20rpx;
  }

  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.order-tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1rpx solid #f5f5f5;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    position: relative;

    &.active {
      color: #0086ff;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background-color: #0086ff;
      }
    }
  }
}

.order-scroll {
  height: calc(100vh - 180rpx);
}

.order-item {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    border-bottom: 1rpx solid #f5f5f5;

    .shop-info {
      display: flex;
      align-items: center;

      image {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        margin-right: 10rpx;
      }

      .shop-name {
        font-size: 28rpx;
        font-weight: bold;
      }
    }

    .order-status {
      font-size: 26rpx;
      color: #ff6b6b;
    }
  }

  // 新增下单时间样式
  .order-time {
    padding: 0 20rpx;
    font-size: 24rpx;
    color: #999;
    margin-bottom: 10rpx;
  }

  .order-products {
    padding: 20rpx;

    .product-item {
      display: flex;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }

      .product-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .product-name {
          font-size: 28rpx;
          color: #333;
        }

        .product-price-count {
          display: flex;
          justify-content: space-between;

          .price {
            font-size: 28rpx;
            color: #ff6b6b;
            font-weight: bold;
          }

          .count {
            font-size: 26rpx;
            color: #999;
          }
        }
      }
    }
  }

  .order-footer {
    padding: 20rpx;
    border-top: 1rpx solid #f5f5f5;

    .order-total {
      font-size: 28rpx;
      text-align: right;
      margin-bottom: 20rpx;

      .price {
        color: #ff6b6b;
        font-weight: bold;
      }
    }

    .order-actions {
      display: flex;
      justify-content: flex-end;

      .action-btn {
        padding: 10rpx 20rpx;
        border: 1rpx solid #ddd;
        border-radius: 30rpx;
        font-size: 24rpx;
        margin-left: 20rpx;

        &.primary {
          background-color: #0086ff;
          color: #fff;
          border-color: #0086ff;
        }
      }
    }
  }
}

.empty-order {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
  }

  text {
    font-size: 28rpx;
    color: #999;
  }
}

.back-to-home {
  text-align: center;
  padding: 20rpx;
}

.back-to-home button {
  background-color: #0086ff;
  color: #fff;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  border: none;
}
</style>    